"use client";

import type { AuthProvider } from "@refinedev/core";
import { message } from "antd";
import { useUserStore, useResourcesStore } from "@store";

export const authProviderClient: AuthProvider = {
  login: async ({ username, password }) => {
    try {
      const response = await fetch("/api/auth/login", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ username, password }),
      });
      const result = await response.json();
      if (result.code === 200 && result.data) {
        // 使用store管理登录状态
        useUserStore.getState().login(result.data.token, result.data.user);
        
        // 获取用户菜单资源
        await useResourcesStore.getState().fetchResources();
        
        return {
          success: true,
          redirectTo: "/",
        };
      } else {
        // 提示错误
        message.error(result.msg || "用户名或密码错误");
        return {
          success: false,
          error: {
            name: "LoginError",
            message: result.msg || "用户名或密码错误",
          },
        };
      }
    } catch (e) {
      return {
        success: false,
        error: {
          name: "LoginError",
          message: "网络错误或服务器异常",
        },
      };
    }
  },
  
  logout: async () => {
    // 使用store管理登出状态
    useUserStore.getState().logout();
    useResourcesStore.getState().reset();
    
    return {
      success: true,
      redirectTo: "/login",
    };
  },
  
  check: async () => {
    const { token, isLogin } = useUserStore.getState();
    
    if (token && isLogin) {
      return {
        authenticated: true,
      };
    }

    return {
      authenticated: false,
      logout: true,
      redirectTo: "/login",
    };
  },
  
  getPermissions: async () => {
    const { userInfo } = useUserStore.getState();
    if (userInfo && userInfo.roles) {
      return userInfo.roles;
    }
    return null;
  },
  
  getIdentity: async () => {
    const { userInfo } = useUserStore.getState();
    return userInfo;
  },
  
  onError: async (error) => {
    if (error.response?.status === 401) {
      return {
        logout: true,
      };
    }

    return { error };
  },
};
